/*
 * @Author: ZhaoZhiqi
 * @Date: 2023-11-03 10:15:08
 * @LastEditors: ZhaoZhiqi
 * @LastEditTime: 2024-02-23 16:31:52
 * @Description:
 * @FilePath: \labtalk-admin\src\api\request.js
 */
import axios from 'axios';
import { notifications } from '@mantine/notifications';

const service = axios.create({
  baseURL: `${import.meta.env.VITE_APP_HTTPURL}`,
  withCredentials: true,
  headers: {
    'content-type': 'application/json',
  },
  timeout: 60000, // 请求超时时间
});

// 响应拦截
service.interceptors.response.use((response) => {
  const res = response.data;
  if (res.status === 435) {
    notifications.show({
      title: '登录超时',
      message: '尚未登录或登陆过期，请重新登陆 🤥',
      autoClose: 1500,
      position: 'top-right',
      color: 'red',
    });

    if(location.pathname !== '/login') {
      setTimeout(() => {
        location.href = '/login';
      }, 1500)
    }
  } else if (res.status !== 200) {
    notifications.show({
      title: '操作失败',
      message: res.desc,
      autoClose: 1500,
      position: 'top-right',
      color: 'red',
    });
  }
  return res;
});

/**
 * @description: 请求接口
 * @param {string} url
 * @param {Method} method
 * @param {object} data
 * @return {*}
 */
const request = (url, method, data) => {
  return new Promise((resolve, reject) => {
    let params = null;
    if (method === 'get' || method === 'GET' || method === 'delete' || method === 'DELETE') {
      params = data;
    }

    let request = null
    if(url === 'login') {
      request = service({
        method: method,
        url: `${url}`,
        params,
        data: data,
      })
    } else {
      request = service({
        headers: {
          'Authorization': localStorage.getItem("labtalk_token")
        },
        method: method,
        url: `${url}`,
        params,
        data: data,
      })
    }
   
    request.then((res) => {
        if (res.status === 200) {
          resolve(res);
        } else {
          reject(res);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
};

export default request;
